package handlers

import (
	"awesome-devops/applications/backend/modules/requests"
	"awesome-devops/applications/models"
	"awesome-devops/applications/nodes"
	"awesome-devops/boot"
	"gitee.com/jjawesomejj/awesome-util/config"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
)

type RunnerHandler struct {
	awesomehttp.HttpBaseHandler
}

func (context *RunnerHandler) GetModuleName() string {
	return "/runner"
}

func (context *RunnerHandler) ActionList() interface{} {
	runner := models.Runner{}
	pageRequest := requests.ResolveDefaultPageRequest(context.HttpContext)
	res, err := runner.Pager(boot.GetDbConnection().Table(runner.TableName()), pageRequest.Page, pageRequest.PageSize, nil)
	if err != nil {
		return err
	}
	nodes.GetNodeManager().RangerRunner(func(describe *nodes.NodeDescribe) {
		for index, value := range res.List {
			if value["unique_id"].(string) == describe.Runner.UniqueId {
				res.List[index]["extension_json"] = describe.RunnerInfo
				res.List[index]["alive"] = describe.IsOnline
			}
		}
	})
	responseJsonStr := commonhelper.JsonEncode(res)
	var responseJson map[string]interface{}
	err = commonhelper.JsonDecodeWithType(responseJsonStr, &responseJson)
	if err != nil {
		return err
	}
	responseJson["unique_id"] = config.GetConfigByKey("unique_id")
	return responseJson
}

func (context *RunnerHandler) ActionSave() interface{} {
	runner := models.Runner{}
	err := runner.AutoSave(&runner, context.HttpContext.PostMany())
	if err != nil {
		return err
	}
	return "success"
}
